import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  DatePicker,
  Drawer,
  Form,
  FormProps,
  Input,
  Select,
  Space,
  TreeSelect
} from 'antd';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';

import Upload from '@/components/upload';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  safePlanInfoAdd,
  safePlanInfoGet,
  safePlanInfoUpdate
} from '@/services/bizApi/anquanjihuaxinxijiekou';
import { findIdByName } from '@/utils';
import { EditableProTable, ProColumns } from '@ant-design/pro-components';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type DataSourceType = {
  key: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
};

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const treeDict = useRef<Record<number, DataNode>>({});
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });

  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const safePlanInfo = useRequest(
    async (id: string) => {
      const res = await safePlanInfoGet({ id });
      const data = res?.data;
      // 回填数据
      form.setFieldsValue({
        ...res?.data,
        finishTime: res?.data?.finishTime ? dayjs(res?.data?.finishTime) : undefined
      });
      setDataSource(
        (data?.detailEntityList?.map((item) => {
          return {
            ...item,
            key: item?.id
          };
        }) as unknown as DataSourceType[]) || []
      );
    },
    {
      manual: true
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      if (!dataSource?.length) {
        store.app?.message.info('请添加计划详情');
        return;
      }
      const query = {
        ...values,
        finishTime: values?.finishTime ? dayjs(values?.finishTime).format('YYYY-MM-DD') : undefined,
        chargeUserName: userInfo?.data?.filter((item) => item.id === values?.chargeUserId)?.[0]
          ?.fullName,
        chargeDeptName: findIdByName(tree?.data || [], values?.chargeDeptId as unknown as string),
        detailEntityList: dataSource
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? safePlanInfoUpdate(query) : safePlanInfoAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDataSource([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            safePlanInfo.run(arg?.rowData?.id as unknown as string);
            // 回填数据
            // form.setFieldsValue({
            //   ...arg.rowData
            // });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDataSource([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '检查内容',
      dataIndex: 'content',
      formItemProps: {
        rules: [{ required: true, message: '请输入检查内容' }]
      }
    },
    {
      title: '备注',
      dataIndex: 'remark',
      formItemProps: {
        rules: [{ required: true, message: '请输入备注' }]
      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      hidden: args?.type === 'detail',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            if (args?.type === 'detail') return;
            action?.startEditable?.(record.key);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            if (args?.type === 'detail') return;
            setDataSource(dataSource.filter((item) => item.key !== record.key));
          }}
        >
          删除
        </a>
      ]
    }
  ];

  return (
    <Drawer
      title={
        {
          add: '新增安全计划',
          edit: '编辑安全计划',
          detail: '安全计划详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="地点"
          name="address"
          rules={[
            {
              required: true,
              message: '请选择地点'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择地点"
            options={
              (store.dict['safetyPlanSite'] || []).map((item) => ({
                value: item.dicValue,
                label: item.dicName
              })) || []
            }
          />
        </Form.Item>
        <Form.Item
          label="名称"
          name="name"
          rules={[
            {
              required: false,
              message: '请输入名称'
            }
          ]}
        >
          <Input style={{ width: '100%' }} placeholder="请输入名称" />
        </Form.Item>
        <Form.Item
          label="类型"
          name="type"
          rules={[
            {
              required: false,
              message: '请选择类型'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择类型"
            options={[
              {
                label: '月计划',
                value: '月计划'
              },
              {
                label: '周计划',
                value: '周计划'
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="负责部门"
          name="chargeDeptId"
          rules={[
            {
              required: true,
              message: '请选择负责部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择负责部门"
            allowClear
          />
        </Form.Item>
        <ProFormSelect
          name="chargeUserId"
          label="负责人"
          placeholder="请选择负责人"
          dependencies={['chargeDeptId']}
          showSearch={true}
          rules={[{ required: true, message: '请选择负责人' }]}
          request={async ({ chargeDeptId }) => {
            const res = await orgUserInfoVoPage({ page: 1, size: 1000, deptId: chargeDeptId });
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Form.Item
          label="计划完成时间"
          name="finishTime"
          rules={[
            {
              required: true,
              message: '请选择计划完成时间'
            }
          ]}
        >
          <DatePicker placeholder="请选择计划完成时间" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="问题概况"
          name="problemOverview"
          rules={[
            {
              required: false,
              message: '请输入问题概况'
            }
          ]}
        >
          <Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} placeholder="请输入问题概况" />
        </Form.Item>
        <Form.Item
          label="附件"
          name="attachment"
          rules={[
            {
              required: false,
              message: '请上传附件'
            }
          ]}
        >
          <Upload
          // base64
          //  accept="image/*"
          >
            <Button>上传</Button>
          </Upload>
        </Form.Item>
        {args?.type === 'detail' && args.rowData.status === 3 && (
          <Form.Item
            label="处理意见"
            name="opinion"
            rules={[
              {
                required: true,
                message: '请输入处理意见'
              }
            ]}
          >
            <Input.TextArea autoSize={{ minRows: 2, maxRows: 4 }} placeholder="请输入处理意见" />
          </Form.Item>
        )}
        <EditableProTable<DataSourceType>
          rowKey="key"
          headerTitle="计划详情"
          maxLength={5}
          // scroll={{
          //   x: 960
          // }}
          recordCreatorProps={{
            position: 'bottom',
            record: () => ({
              key: Date.now()
            })
          }}
          loading={false}
          toolBarRender={() => []}
          columns={columns}
          request={async () => ({
            data: [],
            total: 3,
            success: true
          })}
          value={dataSource}
          onChange={setDataSource}
          editable={{
            type: 'multiple',
            editableKeys,
            onSave: async (rowKey, data, row) => {
              // console.log(rowKey, data, row);
              // await waitTime(2000);
            },
            onChange: setEditableRowKeys
          }}
        />
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
